package com.luceneheritrixbook.index;

import java.io.*;

import jeasy.analysis.MMAnalyzer;

import org.apache.lucene.analysis.*;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.*;

import com.luceneheritrixbook.core.Product;
import com.luceneheritrixbook.searchengine.config.PropertyConfiguration;

public class ProductIndexer {

	private String indexPath = "";
	
	private IndexWriter writer = null;
	
	private Analyzer analyzer = null;
	
	private String dictionary_file = PropertyConfiguration.getWordDictionary();

	public ProductIndexer(String indexPath) throws Exception {
		this.indexPath = indexPath;
		initialize();
	}

	/**
	 * 
	 * @throws Exception
	 */
	private void initialize() throws Exception {
		analyzer = new MMAnalyzer();
//		FileReader reader = new FileReader(dictionary_file);
//		((MMAnalyzer)analyzer).addDictionary(reader);
		writer = new IndexWriter(indexPath, analyzer, true);
	}
	
	
	public void close() {
		try{
			writer.close();
		} catch(Exception e) {
			e.printStackTrace();
			writer = null;
		}
	}
	
	public void addProduct(Product product, int id) throws Exception {
		Thread.sleep(10);		
		Document doc = ProductDocument.buildProductDocument(product, id);
		writer.addDocument(doc);
		Thread.sleep(10);
	}
	
	public void optimizeIndex() throws Exception {
		writer.optimize();
	}
	

}
